import Vue from 'vue';
import Vuex	from 'vuex';
import api from '@/common/api'
import jwx from '@/utils/jwx.js'

Vue.use(Vuex);
const info = {
	state: {
		config: '',
		location: '',
		userplus: ''
	},
	mutations: {
		setInfo(state,data){
			state.config = data
		},
		setLocation(state,data){
			state.location = data
		},
		setUserplus(state,data){
			state.userplus = data
		},
	},
	actions: {
		getLocation({
			commit
		}) {
			
			let province,city,district,township,lng,lat
			return new Promise((resolve, reject) => {
				// #ifdef H5
				jwx.getlocation((res) => {
					lng = res.longitude
					lat = res.latitude
					api.post('/getlocation', {
						lng: res.longitude,
						lat: res.latitude,
					}).then(response => {
						if (response.code == 1) {
							
							province = response.data.province
							if (response.data.city === '[]' || response.data.city.length === 0) {
								city = response.data.province
							} else {
								city = response.data.city
							}
							district = response.data.district
							township = response.data.township
							let data = {
								province,city,district,township,lng,lat
							}
							commit('setLocation', data);
							resolve(data)
						}
					}).catch(e => {
						reject('')
					})
				})
				// #endif
				
				// #ifndef H5
				uni.getLocation({
					type: 'wgs84',
					success: function(res) {
						lng = res.longitude
						lat = res.latitude
						api.post('/getlocation', {
							lng: res.longitude,
							lat: res.latitude,
						}).then(response => {
							if (response.code == 1) {
								
								province = response.data.province
								if (response.data.city === '[]' || response.data.city.length === 0) {
									city = response.data.province
								} else {
									city = response.data.city
								}
								district = response.data.district
								township = response.data.township
								let data = {
									province,city,district,township,lng,lat
								}
								commit('setLocation', data);
								resolve(data)
							}
						}).catch(e => {
							reject('')
						})
					},
					fail:(e)=>{
						
						reject('')
					}
				});
				// #endif
			})
		},
		getUserplus({
			commit
		}) {
			
			let province,city,district,township,lng,lat
			return new Promise((resolve, reject) => {
				if(uni.getStorageSync('token')){
					api.post('/index').then(response => {
						if (response.code == 1) {
							
							commit('setUserplus', response.data.userplus);
							resolve(response.data.userplus)
						}
					}).catch(e => {
						reject('')
					})
				}else{
					reject('')
				}
				
			})
		},
	}
}
const store = new Vuex.Store({
	...info
});

export default store;